
<template>
    <div v-if="gameData" class="full_wrapper">
      <div class="main">
        <div class="xb_pageCont xb_flex">
          <div class="page_body xb_head_padding" id="xb_page_body">
            <div id="xb_chat_content" style="padding: 0">
              <div class="xb_conversation_item">
                <div class="xb_conv_wrap_left">
                  <img class="xb_avatar_left" src="/img/quce.png">
                  <div class="xb_tri_left"></div>
                  <div class="xb_tri_left1"></div>
                  <div class="xb_conv_left">
                    {{gameData.desc}}
                  </div>
                </div>
              </div>

              <div v-if="gameData.logo" class="xb_conversation_item">
                <div class="xb_conv_wrap_left">
                  <img class="xb_avatar_left" src="/img/quce.png">
                  <div class="xb_tri_left"></div><div class="xb_tri_left1"></div>
                  <div class="xb_conv_left  xb_conv_left_img img-longtap-fix">
                    <img :src="$axios.defaults.proxyImage(gameData.logo)" class="xb_sendimg">
                    <img :src="$axios.defaults.proxyImage(gameData.logo)" class="xb_sendimg_opcity">
                  </div>
                </div>
              </div>
              <div class="xb_conversation_item" v-if="started">
                <div class="xb_conv_wrap_right">
                  <img class="xb_avatar_right" src="/img/usericon.png">
                  <div class="xb_tri_right"></div>
                  <div class="xb_tri_right1"></div>
                  <div class="xb_conv_right">开始</div>
                </div>
              </div>
              <template v-for="(question, idx) in selectedQuestions">
                <div :key="idx + 'question_indexes_box'" class="question_indexes_box">
                  <p class="question_indexes">第{{idx+1}}题/共{{gameData.question.length}}题</p>
                </div>
                <div :key="idx + 'xb_conversation_item'" class="xb_conversation_item">
                  <div class="xb_conv_wrap_left">
                    <img class="xb_avatar_left" src="/img/quce.png">
                    <div class="xb_tri_left"></div>
                    <div class="xb_tri_left1"></div>
                    <div class="xb_conv_left">
                      {{question.question}}
                    </div>
                  </div>
                </div>
                <div :key="idx + 'question_audio_box'" v-if="question.audio" class="xb_conversation_item">
                  <div class="xb_conv_wrap_left">
                    <img class="xb_avatar_left" src="/img/quce.png">
                    <div class="xb_tri_left"></div>
                    <div class="xb_tri_left1"></div>
                    <div class="xb_conv_left audio_pause" @click.prevent="playSound(question)">
                      <span class="audio_icon_box">
                          <img v-if="!getAudio(question).playing" src="/img/01.png" class="audio_ani_btn">
                          <img v-else src="/img/02.gif" class="audio_ani_btn">
<!--                          <span class="audio_timer" id="" style="display: none;">11"</span>-->
                      </span>
                      <span v-if="!getAudio(question).player" class="audio_reddot"></span>
                    </div>
                  </div>
                </div>
                <div  :key="idx + 'question_img_box'" v-if="question.img" class="xb_conversation_item">
                  <div class="xb_conv_wrap_left">
                    <img class="xb_avatar_left" src="/img/quce.png">
                    <div class="xb_tri_left"></div><div class="xb_tri_left1"></div>
                    <div class="xb_conv_left  xb_conv_left_img img-longtap-fix">
                      <img v-lazy="$axios.defaults.proxyImage(question.img)" class="xb_sendimg">
                      <img v-lazy="$axios.defaults.proxyImage(question.img)" class="xb_sendimg_opcity">
                    </div>
                  </div>
                </div>
                <div :key="idx + 'question_options_box'" class="question_options_box">
                  <div class="question_options_container">
                    <div class="question_options_image_box" style="margin: 0">
                      <template v-for="(answer, akey) in question.answer">
                        <div v-if="answer.img" :key="idx + '-' + akey + '-img'" class="option_image_item" :style="{backgroundImage: 'url(' + $axios.defaults.proxyImage(answer.img) + ')'}">
                          <img src="/img/unselect.png" style="display: block;width: 100%;opacity: 0;">
                          <span class="options_key">{{akey}}</span>
                        </div>
                      </template>
                    </div>
                    <div class="question_options_desc_box">
                      <template v-for="(answer, akey) in question.answer">
                        <div :key="idx+'-'+akey+'-option'" class="options_question_item" :class="question.selected===akey?'options_question_item_select':''" @click="selectAnswer(question, akey)">
                          <span style="font-size: 16px;line-height: 24px">{{akey}}.{{answer.title}}</span>
                          <img src="/img/unselect.png" class="options_question_icon options_question_uncheck">
                          <img src="/img/select.png" class="options_question_icon options_question_select">
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
                <template v-if="question.selected">
                  <div :key="idx + 'user-xb_conversation_item'" class="xb_conversation_item">
                    <div class="xb_conv_wrap_right">
                      <img class="xb_avatar_right" src="/img/usericon.png">
                      <div class="xb_tri_right"></div>
                      <div class="xb_tri_right1"></div>
                      <div class="xb_conv_right">{{question.selected}}.{{question.answer[question.selected].title}}</div>
                    </div>
                  </div>
                </template>
              </template>
              <div v-if="(status&statusInputting)!==0" class="xb_conversation_item">
                <div class="xb_conv_wrap_left">
                  <img class="xb_avatar_left" src="/img/quce.png">
                  <div class="xb_tri_left"></div>
                  <div class="xb_tri_left1"></div>
                  <div class="xb_conv_left  ">
                    请输入名字或昵称，立即为你分析结果
                  </div>
                </div>
              </div>
              <div v-if="(status&statusInputted)!==0" class="xb_conversation_item">
                <div class="xb_conv_wrap_right">
                  <img class="xb_avatar_right" src="/img/usericon.png">
                  <div class="xb_tri_right"></div>
                  <div class="xb_tri_right1"></div>
                  <div class="xb_conv_right">{{userName}}</div>
                </div>
              </div>
              <div v-if="(status&statusAnalysing)!==0" class="xb_conversation_item">
                <div class="xb_conv_wrap_left">
                  <img class="xb_avatar_left" src="/img/quce.png">
                  <div class="xb_tri_left"></div>
                  <div class="xb_tri_left1"></div>
                  <div class="xb_conv_left  ">
                    正在为你分析结果...
                  </div>
                </div>
              </div>
              <template v-if="(status&statusEnd)!==0">
                <div class="xb_conversation_item">
                  <div class="xb_conv_wrap_left">
                    <img class="xb_avatar_left" src="/img/quce.png">
                    <div class="xb_tri_left"></div><div class="xb_tri_left1"></div>
                    <div class="xb_conv_left  xb_conv_left_img img-longtap-fix">
                      <div style="overflow: hidden;" @click="modelVisible=true">
                        <img v-lazy="img" class="xb_sendimg" style="margin-bottom: -55px !important;">
                        <img v-lazy="img" class="xb_sendimg_opcity longtap-img">
                      </div>
                    </div>
                  </div>
                </div>
                <div class="xb_conversation_item">
                  <div class="xb_conv_wrap_left">
                    <img class="xb_avatar_left" src="/img/quce.png">
                    <div class="xb_tri_left"></div>
                    <div class="xb_tri_left1"></div>
                    <div class="xb_conv_left">
                      长按上方图片保存你的结果卡片
                    </div>
                  </div>
                </div>
                <div class="xb_btn_area" style="display: table;">
                  <div class="xb_btn_container">
                    <router-link  class="btn_basic wechatGreen text_holder" to="/">
                      更多测试
                    </router-link>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
      <!-- 按钮div -->
      <template v-if="selectedQuestions.length===0">
        <div class="xb_btn_area" style="display: table;">
          <div class="xb_btn_container">
            <a id="start_game" @click="start" href="javascript:void(0)" class="btn_basic wechatGreen text_holder">开始</a>
          </div>
        </div>
      </template>
      <div v-if="status === statusInputting" class="xb_btn_area" style="display: table;">
        <div class="xb_btn_container">
        <span class="shotinput" style="height: 47px;">
            <input id="btn_input" type="text" placeholder="请输入你的昵称" v-model="userName">
        </span>
          <span id="input_submit" @click="checkinput()" href="javascript:void(0)" class="btn_input wechatGreen text_holder">发送</span>
        </div>
      </div>

<!--      <div id="morebtn_prompt" class="morebtn_prompt">-->
<!--        <img class="morebtn_prompt_hand" src="/img//hand.png" alt="">-->
<!--        <img class="morebtn_prompt_arrow" src="/img/arrow.png" alt="">-->
<!--      </div>-->

      <div v-if="modelVisible" id="img-model" @click="modelVisible=false">
        <img :src="img" style="width: 100%;height: auto">
      </div>
    </div>
</template>

<script>
export default {
  name: 'game',
  data(){
    return {
      statusInputting: 1 << 0,
      statusInputted: 1 << 1,
      statusAnalysing: 1 << 2,
      statusEnd: 1 << 3,
      gameData:null,
      started: false,
      selectedQuestions: [],
      questionIndex: 0,
      result: null,
      img: "",
      modelVisible: false,
      userName:"",
      status: "",
      qrcodeLocations:{
        6466: (resWidth, resHeight)=> {
          let width = 130;
          return {
            x: (resWidth-width)/2,
            y: resHeight - width - 55,
            width: width
          }
        }
      },
      audios:[],
    }
  },
  created(){
    this.imgEvents.setLoaded(()=>{
      this.$nextTick(()=>{
        this.scrollToBottom();
      })
    });
    let id = this.$route.query.id;
    if(id) {
      this.$axios.get("/game/" + id).then((resp) => {
        let data = resp.data;
        if (data.game) {
          let audios = [];
          for(let key in data.game.question) {
            let question = data.game.question[key];
            question.selected = "";
            question.Index = key;
            audios[key] = {
              playing: false,
              player: null,
            };
          }
          this.audios = audios;
          this.gameData = data.game;
          document.title = this.gameData.title;
        }
      })
    }
  },
  watch:{
    selectedQuestions: {
      handler: function () {
        this.$nextTick(()=>{
          this.scrollToBottom();
        })
      },
      deep: true,
    },
    status: {
      handler: function () {
        this.$nextTick(()=>{
          this.scrollToBottom();
        })
      }
    }
  },
  methods:{
    getAudio (question) {
      return this.audios[question.Index]
    },
    scrollToBottom () {
      let xb_page_body = this.$el.querySelector("#xb_page_body");
      let xb_chat_content = this.$el.querySelector("#xb_chat_content");
      let offset = xb_chat_content.offsetHeight - xb_page_body.offsetHeight;
      if(offset>0) {
        let rate = 10;
        let int = setInterval(function () {
          xb_page_body.scrollTop+=20;
          if(xb_page_body.scrollTop>=offset-1) {
            clearInterval(int)
          }
        }, rate);
      }
    },
    getQRCodeLocation (id) {
      let location = this.qrcodeLocations[id];
      if(location) {
        return location
      } else {
        return (resWidth, resHeight)=> {
          return {
            x: 25,
            y: resHeight - 100 - 10,
            width: 100,
          }
        };
      }
    },
    playSound (question) {
      let audio = this.audios[question.Index];
      if(!audio.player) {
        audio.player = new Audio(this.$axios.defaults.proxyImage(question.audio))
      }
      if(audio.player.paused) {
        for(let other of this.audios) {
          if(other.playing) {
            other.player.pause();
            other.playing = false;
          }
        }
        audio.player.play();
        audio.playing = true;
        let int = setInterval(()=>{
          if(audio.player.paused) {
            audio.playing = false;
            clearInterval(int);
          }
        }, 200)
      } else {
        audio.player.pause();
        audio.playing = false;
      }
    },
    checkinput(){
      if(!this.userName) {
        alert("请输入用户名")
      } else {
        this.status |= this.statusInputted;
        setTimeout(()=>{
          this.getResult();
        }, 1000);
      }
    },
    start() {
      this.started = true;
      this.setQuestion(0);
    },
    setQuestion(idx) {
      let question = this.gameData.question[idx];
      question.selected="";
      setTimeout(()=>{
        this.selectedQuestions.push(question);
      }, 1000);
      this.questionIndex = idx;
    },
    selectAnswer(question, key) {
      if(!question.selected) {
        question.selected = key;
        if(this.gameData.question.length>this.questionIndex+1) {
          let next = question.answer[key].next;
          if(next&&(next-0)>0) {
            next-=0;
            this.questionIndex = next-2;
          }
          this.setQuestion(this.questionIndex + 1);
        } else {
          if(this.gameData.name_config) {
            setTimeout(()=>{
              this.status = this.statusInputting;
            }, 1000);
          } else {
              this.getResult();
          }
        }
      }
    },
    getResult() {
      this.status |= this.statusAnalysing;
      let options = [];
      for(let question of this.selectedQuestions) {
        let answer = question.answer[question.selected];
        let weight = answer.weight;
        if(weight > 0) {
          options.push(weight)
        } else {
          options.push(question.selected.toUpperCase())
        }
      }
      let option = options.join(",");
      this.$axios.get("/result", {params: {id: this.$route.query.id, option: option}}).then((resp)=>{
          let data = resp.data;
          if(data.result){
            this.result = data.result;
            let $this = this;
            let resultimg = new Image();
            let nameConfig = null;
            if(this.gameData.name_config) {
              nameConfig = JSON.parse(this.gameData.name_config);
              // if(this.result.threshold && nameConfig[this.result.threshold]){
              //   nameConfig = nameConfig[this.result.threshold];
              // }
            }
            let headImgConfig = null;
            if(this.gameData.head_img_config) {
              headImgConfig = JSON.parse(this.gameData.head_img_config);
            }
            resultimg.crossOrigin = '';
            resultimg.onload = function () {
              let canvas = document.createElement('canvas');
              let ctx = canvas.getContext('2d');
              canvas.width = resultimg.width;
              canvas.height = resultimg.height;
              ctx.drawImage(resultimg, 0, 0);
              if(nameConfig) {
                ctx.font = "28px sans-serif";
                ctx.fillStyle = "#ffa8ca";
                ctx.textAlign = nameConfig["align"]?nameConfig["align"]:"left";
                if (!nameConfig.x) {
                  nameConfig.x = resultimg.width/2
                }
                ctx.fillText($this.userName, nameConfig.x, nameConfig["y"] - 0 + 28 );
              }
              if(headImgConfig) {
                let headImg = new Image();
                headImg.crossOrigin = "";
                headImg.onload = function () {
                  ctx.drawImage(headImg, headImgConfig['x'], headImgConfig['y'], headImgConfig['width'], headImgConfig['height']);
                  $this.img = canvas.toDataURL();
                };
                headImg.src="/img/usericon.png";
              }
              let qrcode = new Image();
              qrcode.crossOrigin = '';
              qrcode.onload = function () {
                let qr = $this.getQRCodeLocation($this.gameData.id)(resultimg.width, resultimg.height);
                ctx.drawImage(qrcode, qr.x, qr.y, qr.width, qr.width);
                $this.img = canvas.toDataURL();
              };
              let QRCode = require('qrcode');
              QRCode.toDataURL(location.origin + "/share?id=" + $this.gameData.id + "&title=" + $this.gameData.title)
              .then((dataURL) => {
                $this.gameHistory.setHistory({
                  id: $this.gameData.id,
                  title: $this.gameData.title,
                  desc: $this.gameData.desc,
                  img: $this.gameData.img,
                  view: ($this.gameData.view-0)/10000,
                });
                qrcode.src = dataURL;
              });
            };
            if(this.gameData.special_result_data) {
              let result_data = JSON.parse(this.gameData.special_result_data);
              let img = result_data[this.result.content.threshold];
              if(img) {
                resultimg.src = this.$axios.defaults.proxyImage(img);
              } else {
                resultimg.src = this.$axios.defaults.proxyImage(this.result.content.img);
              }
            } else {
              resultimg.src = this.$axios.defaults.proxyImage(this.result.content.img);
            }
            setTimeout(()=>{
              this.status |= this.statusEnd;
            }, 1000);
          }
      });
    },
  }
}
</script>
<style>
  #img-model{
    background: rgba(0, 0, 0, 0.93);
    z-index: 999;
    position: absolute;
    top: 0;
    bottom: 0;
    left:0;
    right:0;
    display: flex;
    align-items: center;
  }
  .option_image_item{
    margin: 2px;
  }
</style>
